package com.xiaochen.manager.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.xiaochen.manager.mapper.CategoryMapper;
import com.xiaochen.model.vo.product.CategoryExcelVo;

import java.util.List;

/**
 * (Excel导入数据)监听器
 *
 * 不能被spring容器管理,要不然会出问题
 */
public class ExcelListener<T> implements ReadListener<T> {

    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 100;

    /**
     * 缓存的数据
     */
    private List<T> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    //构造器传递mapper,操作数据库
    private CategoryMapper categoryMapper;
    public ExcelListener(CategoryMapper categoryMapper){
        this.categoryMapper = categoryMapper;
    }

    // 从第二行开始读取,把每行读取到的内容封装到 T对象 里面
    @Override
    public void invoke(T t, AnalysisContext analysisContext) {
        // 把每行数据对象放到 cachedDataList 里面
        cachedDataList.add(t);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (cachedDataList.size() >= BATCH_COUNT) {
            // 批量添加
            saveData();
            // 添加完成之后 , 需要将这个 cachedDataList缓存 清空
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        if (!cachedDataList.isEmpty()) {
            saveData();
            cachedDataList.clear();
        }
    }

    /**
     * 批量添加
     */
    private void saveData() {
        categoryMapper.insertBatch((List<CategoryExcelVo>)cachedDataList);
    }
}
